<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="70%"
    @ok="handleSubmit"
    :maskClosable="false"
  >
    <BasicForm @register="registerForm">
      <template #interfaceSlot>
        <FormItem>
          <Collapse
            :default-active-key="21"
            class="w-full bg-white rounded-md"
            :bordered="true"
            expand-icon-position="end"
            :accordion="true"
          >
            <Collapse.Panel
              :header="option.name"
              v-for="option in checkGroupOptions"
              :key="option.id"
            >
              <div
                :style="{
                  borderBottom: '1px solid #E9E9E9',
                  borderBottomStyle: 'dashed',
                  padding: '0 0 0.4rem 0',
                  marginBottom: '0.8rem',
                }"
              >
                <!-- v-model:checked="checkAll" -->
                <Checkbox
                  @change="onCheckAllChange"
                  :id="option.id"
                  :indeterminate="option.indeterminate"
                  :checked="option.checkedAll"
                >
                  全选
                </Checkbox>
              </div>
              <FormItemRest>
                <!-- <CheckboxGroup v-model:value="option.selected" :options="option.options" /> -->
                <!-- :id="opt.id" name="checkboxgroup"-->
                <CheckboxGroup v-model:value="option.selected" name="checkboxgroup" :id="option.id">
                  <Checkbox v-for="opt in option.options" :key="opt.value" :value="opt.value">
                    {{ opt.label }}
                  </Checkbox>
                </CheckboxGroup>
              </FormItemRest>
            </Collapse.Panel>
          </Collapse>
          <!-- h-32 -->
        </FormItem>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { computed, reactive, watch } from 'vue';
  import { BasicForm, useForm } from '@/components/Form';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
  import { CollapseContainer } from '@/components/Container';
  import { Checkbox, CheckboxGroup, FormItem, FormItemRest, Collapse } from 'ant-design-vue';

  import { interfaceFormSchema } from './role.data';
  import { CreateRoleInterfaceParams, CheckBoxOption } from '@/api/system/systemModel';
  import { createRoleInterface, getRoleInterfaceList } from '@/api/system/role';
  import { getAll } from '@/api/system/interfaces';

  import { useMessage } from '@/hooks/web/useMessage';
  import { useI18n } from '@/hooks/web/useI18n';
  import { start } from 'nprogress';

  const { createMessage } = useMessage();
  const { t } = useI18n();

  const emit = defineEmits(['success', 'register']);

  interface CheckGroupType {
    id: string;
    name: string;
    checkedAll: boolean;
    checkedList: string[];
    selected: string[];
    indeterminate: boolean;
    options: CheckBoxOption[];
  }

  function onCheckAllChange(e) {
    let id: string = e.target.id;
    let checked: boolean = e.target.checked;
    checkGroupOptions.forEach((item) => {
      if (item['id'] == id) {
        item.checkedAll = !item.checkedAll;
        if (checked) {
          item.selected = item.checkedList;
        } else {
          item.selected = [];
        }
      }
    });
  }

  let roleId: string;

  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
    labelWidth: 90,
    baseColProps: { span: 24 },
    schemas: interfaceFormSchema,
    showActionButtonGroup: false,
  });

  let checkGroupOptions = reactive<CheckGroupType[]>([]);

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields();
    setDrawerProps({ confirmLoading: false });
    roleId = data.record?.id;
    checkGroupOptions = reactive<CheckGroupType[]>([]);

    setFieldsValue({
      ...data.record,
    });

    // TODO 授权接口选中有待处理
    const checktedOptionsList = await getRoleInterfaceList(roleId);

    const dataList = await getAll();
    for (let key in dataList) {
      let item = dataList[key];
      let optionIdList: string[] = [];
      let selectedOptions: string[] = [];
      let interfaceOptions: CheckBoxOption[] = [];
      for (let indx in item['dataList']) {
        let data = item['dataList'][indx];
        optionIdList.push(data['id']);
        checktedOptionsList.forEach((item: any) => {
          if (item == data['id']) {
            selectedOptions.push(data['id']);
          }
        });
        // checktedOptionsList.map((item: any) => {
        //   if (item == data['id']) {
        //     selectedOptions.push(data['id']);
        //   }
        // });
        interfaceOptions.push({
          label: `${data['name']}[${data['url']}]`,
          value: data['id'],
          checked: true,
        });
      }
      let obj: CheckGroupType = {
        id: String(item['classId']),
        name: item['className'],
        checkedAll: selectedOptions.length == optionIdList.length,
        checkedList: optionIdList,
        selected: selectedOptions,
        indeterminate:
          selectedOptions.length > 0 && selectedOptions.length < optionIdList.length ? true : false,
        options: interfaceOptions,
      };

      checkGroupOptions.push(obj);
    }

    // 监听每一个CheckGroupType实例的selected属性
    checkGroupOptions.forEach((group) => {
      watch(
        () => group.selected,
        (newSelected) => {
          if (group.checkedList.length == newSelected.length) {
            group.indeterminate = false;
            group.checkedAll = true;
          } else if (newSelected.length > 0) {
            group.indeterminate = true;
            group.checkedAll = false;
          } else if (newSelected.length == 0) {
            group.indeterminate = false;
            group.checkedAll = false;
          }
        },
        {
          deep: true,
        },
      );
    });
    // for (const item of dataList) {
    //   console.log(item);
    //   // interfaceOptions.push({
    //   //   label: item['name'],
    //   //   value: item['id'],
    //   // });
    // }

    // updateSchema({
    //   field: 'field5',
    //   defaultValue: defaultVal,
    //   componentProps: {
    //     options: interfaceOptions,
    //   },
    // });
  });

  const getTitle = computed(() => '接口授权');

  async function handleSubmit() {
    try {
      // const values = await validate();
      let selected: string[] = [];
      setDrawerProps({ confirmLoading: true });
      for (let key in checkGroupOptions) {
        let item = checkGroupOptions[key];
        selected.push(...item['selected']);
      }
      // console.log(values);
      // TODO custom api

      let params: CreateRoleInterfaceParams = {
        role_id: roleId,
        interface_ids: selected.join(','),
      };
      const { code, message } = await createRoleInterface(params);
      if (code == 0) {
        createMessage.success(t('sys.api.operationSuccess'), 1, () => {
          closeDrawer();
          emit('success');
        });
      } else {
        createMessage.error(message);
      }
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>

<style lang="less">
  .vben-basic-drawer .ant-drawer-body {
    background-color: #f5f5f5;
  }
</style>
